import React, { useState, useEffect, useCallback, useMemo } from "react";
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
  CardDescription,
} from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
import { useToast } from "@/components/ui/use-toast";
import { Alert, AlertDescription } from "@/components/ui/alert";
import {
  Save,
  Calculator,
  AlertTriangle,
  Info,
  Settings2,
  Layers,
  ChevronDown,
  Anchor,
} from "lucide-react";
import { TooltipProvider } from "@/components/ui/tooltip";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectValue,
  SelectTrigger,
} from "@/components/ui/select";
import {
  Collapsible,
  CollapsibleContent,
  CollapsibleTrigger,
} from "@/components/ui/collapsible";
import FormulaDisplay from "../FormulaDisplay";

import { ConductorSpecAPI } from "@/api/ConductorSpec";
import { DyneemaRopeSpecAPI } from "@/api/DyneemaRopeSpec";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";

export default function BearingCableCalculator({
  scheme,
  onUpdate,
  crossingPoint,
}) {
  // 初始化时打印传入的参数
  console.log("[BearingCableCalculator] 组件初始化 - 传入参数:");
  console.log("  scheme:", scheme);
  console.log("  crossingPoint:", crossingPoint);
  console.log("  onUpdate方法存在:", typeof onUpdate === "function");

  const { toast } = useToast();
  const [conductorSpec, setConductorSpec] = useState(null);
  const [allConductorSpecs, setAllConductorSpecs] = useState([]);
  const [isLoadingConductorSpec, setIsLoadingConductorSpec] = useState(true);

  const [allDyneemaSpecs, setAllDyneemaSpecs] = useState([]);
  const [selectedDyneemaSpec, setSelectedDyneemaSpec] = useState(null);
  const [isLoadingDyneemaSpecs, setIsLoadingDyneemaSpecs] = useState(true);

  const [isAdvancedOpen, setIsAdvancedOpen] = useState(false);
  const [isNettingWeightDetailsOpen, setIsNettingWeightDetailsOpen] =
    useState(false);

  // 初始化参数状态
  const [conductorParams, setConductorParams] = useState(() => {
    const initialParams = {
      conductorNumber: scheme.conductorBasicParams?.conductorCount ?? 1,
      maxSagAtHighestTemp: scheme.conductorBasicParams?.maximumSag ?? null,
    };
    console.log("[BearingCableCalculator] 初始化导线参数:", scheme);
    return initialParams;
  });

  const [bearingCableParams, setBearingCableParams] = useState(() => {
    const initialParams = {
      safetyFactor: scheme.carryingCableConfig?.safetyFactor ?? 3, //	安全系数
      dyneemaSafetyFactor: scheme.safetyFactor ?? 6, //	安全系数
      nettingRopeCount: scheme.carryingCableConfig?.ropeCount ?? 0, //	绳数量(根)
      nettingRopeLength: scheme.carryingCableConfig?.ropeLengthPerRoot ?? 0, //	绳长度(m/根)
      nettingRopeUnitWeight:
        scheme.carryingCableConfig?.ropeWeightPerMeter ?? 0, //	绳单重(kg/m)

      nettingAttachmentTotalWeight:
        scheme.carryingCableConfig?.accessoryTotalWeight ?? 0, //	附件总重(kg)
      nettingInsulatorRodLength:
        scheme.carryingCableConfig?.barLengthPerRoot ?? 0, //	杆长度(m/根)
      nettingInsulatorRodUnitWeight:
        scheme.carryingCableConfig?.barWeightPerMeter ?? 0, //	杆单重(kg/m)
      cableBreakingForce: scheme.carryingCableConfig?.breakingForce, ////	破断力(kN)
      cableType: scheme.carryingCableConfig?.cableType || "dyneemaRope", //	承载索类型
      cableDiameter: scheme.bearingCableDiameter ?? 17,
      dyneemaSpecId: scheme.carryingCableConfig?.dyneemaRopeSpec || "", //迪尼玛绳规格
      highSuspensionPointHeight:
        scheme.carryingCableConfig?.highSideSuspension ?? null, //高侧悬挂点高程 (m)

      nettingInsulatorRodCount:
        scheme.carryingCableConfig?.insulatorBarCount ?? 0, //绝缘杆数量(根)

      lowSuspensionPointHeight:
        scheme.carryingCableConfig?.lowSideSuspension ?? null, //	低侧悬挂点高程 (m)
      minClearance: scheme.carryingCableConfig?.minClearance ?? 6, //最小净空(m)

      fallenCircuitType: scheme.fallenCircuitType || "single",
      fallenConductorCount:
        scheme.anchorRopeCalculation?.splitConductorCount ?? 1, // 落网分裂导线数量n
      anchorRopeSafetyFactor: scheme.anchorRopeCalculation?.safetyFactor ?? 3.0, // 	锚网绳安全系数(Ks)
      anchorRopeMaterial: scheme.anchorRopeCalculation?.selectedMaterial || "", // 选用材料
      anchorRopeSpec: scheme.anchorRopeCalculation?.selectedSpecification || "", // 	选用规格
    };
    console.log("[BearingCableCalculator] 初始化承载索参数:", initialParams);
    return initialParams;
  });

  // 解析导线类型
  const conductorType =
    scheme.insulband?.parametersWire.conductorType ??
    (crossingPoint?.conductorType ? crossingPoint.conductorType : null);
  console.log("[BearingCableCalculator] 解析得到的导线类型:", conductorType);

  const localNettingLength = scheme.calculatedNettingLength || null;
  console.log("[BearingCableCalculator] 局部封网长度:", localNettingLength);

  const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

  const apiCallWithRetry = useCallback(
    async (apiCall, maxRetries = 3, initialDelay = 2000) => {
      console.log(`[API] 准备调用API，最大重试次数: ${maxRetries}`);
      for (let attempt = 1; attempt <= maxRetries; attempt++) {
        try {
          console.log(`[API] 第${attempt}/${maxRetries}次尝试调用`);
          const result = await apiCall();
          console.log(`[API] 第${attempt}次调用成功`);
          return result;
        } catch (error) {
          const isRateLimitError =
            error.message?.includes("429") ||
            (error.response && error.response.status === 429);

          if (isRateLimitError && attempt < maxRetries) {
            const delayTime =
              initialDelay * Math.pow(2, attempt - 1) + Math.random() * 1000;
            console.warn(
              `[API] 速率限制，等待 ${Math.round(delayTime)}ms 后重试...`
            );
            await delay(delayTime);
            continue;
          }
          console.error(`[API] 调用失败，尝试次数: ${attempt}`, error);
          throw error;
        }
      }
    },
    []
  );

  useEffect(() => {
    const loadAllSpecs = async () => {
      console.log("[导线规格] 开始加载导线规格数据");
      if (!ConductorSpecAPI) {
        console.error("[导线规格] ConductorSpecAPI 未定义，无法加载数据");
        toast({
          variant: "destructive",
          title: "组件加载错误",
          description: "导线规格组件未能成功加载，请刷新页面重试。",
        });
        setAllConductorSpecs([]);
        setIsLoadingConductorSpec(false);
        return;
      }
      try {
        console.log("[导线规格] 等待3000ms后开始请求数据");
        await delay(3000);
        const specs = await apiCallWithRetry(() => {
          console.log("[导线规格] 调用ConductorSpecAPI.getList()");
          return ConductorSpecAPI.getList();
        });
        console.log("[导线规格] 数据请求成功，原始响应:", specs);
        const data = Array.isArray(specs.data) ? specs.data : [];
        console.log(`[导线规格] 解析得到${data.length}条导线规格数据`);
        setAllConductorSpecs(data);
      } catch (error) {
        console.error("[导线规格] 加载失败:", error);
        setAllConductorSpecs([]);
        if (!error.message?.includes("429")) {
          toast({
            variant: "destructive",
            title: "导线规格库加载失败",
            description: "部分计算功能可能受限",
          });
        }
      } finally {
        console.log("[导线规格] 加载过程完成，设置isLoading为false");
        setIsLoadingConductorSpec(false);
      }
    };
    loadAllSpecs();
  }, [apiCallWithRetry, toast]);

  useEffect(() => {
    const loadDyneemaSpecs = async () => {
      console.log("[迪尼玛绳规格] 开始加载迪尼玛绳规格数据");
      setIsLoadingDyneemaSpecs(true);
      if (!DyneemaRopeSpecAPI) {
        console.error("[迪尼玛绳规格] DyneemaRopeSpecAPI 未定义，无法加载数据");
        toast({
          variant: "destructive",
          title: "组件加载错误",
          description: "迪尼玛绳规格组件未能成功加载，请刷新页面重试。",
        });
        setAllDyneemaSpecs([]);
        setIsLoadingDyneemaSpecs(false);
        return;
      }
      try {
        await delay(80);
        const specs = await apiCallWithRetry(() => {
          console.log("[迪尼玛绳规格] 调用DyneemaRopeSpecAPI.getList()");
          return DyneemaRopeSpecAPI.getList();
        });
        console.log("[迪尼玛绳规格] 数据请求成功，原始响应:", specs);
        const data = Array.isArray(specs.data) ? specs.data : [];
        console.log(`[迪尼玛绳规格] 解析得到${data.length}条迪尼玛绳规格数据`);
        setAllDyneemaSpecs(data);
      } catch (error) {
        console.error("[迪尼玛绳规格] 加载失败:", error);
        setAllDyneemaSpecs([]);
        if (!error.message?.includes("429")) {
          toast({
            variant: "destructive",
            title: "迪尼玛绳规格库加载失败",
            description: "迪尼玛绳选型功能暂时不可用",
          });
        }
      } finally {
        console.log("[迪尼玛绳规格] 加载过程完成，设置isLoading为false");
        setIsLoadingDyneemaSpecs(false);
      }
    };
    loadDyneemaSpecs();
  }, [apiCallWithRetry, toast]);

  useEffect(() => {
    const loadConductorSpec = () => {
      console.log("[导线规格匹配] 开始匹配导线规格，条件:");
      console.log("  conductorType:", conductorType);
      console.log("  可用规格数量:", allConductorSpecs.length);

      if (conductorType && allConductorSpecs.length > 0) {
        const selectedSpec = allConductorSpecs.find(
          (s) => s.model === conductorType
        );
        if (selectedSpec) {
          console.log(`[导线规格匹配] 找到匹配的导线规格:`, selectedSpec);
          setConductorSpec(selectedSpec);
        } else {
          console.log(
            `[导线规格匹配] 未找到型号为"${conductorType}"的导线规格`
          );
          setConductorSpec(null);
          toast({
            variant: "warning",
            title: "导线型号未找到",
            description: `知识库中未找到型号为 "${conductorType}" 的导线规格。`,
          });
        }
      } else {
        console.log("[导线规格匹配] 缺少导线类型或规格列表为空");
        setConductorSpec(null);
      }
    };

    if (!isLoadingConductorSpec) {
      loadConductorSpec();
    } else {
      console.log("[导线规格匹配] 等待导线规格加载完成");
    }
  }, [conductorType, allConductorSpecs, toast, isLoadingConductorSpec]);

  // 优化迪尼玛绳规格匹配逻辑
  useEffect(() => {
    console.log("[迪尼玛绳规格匹配] 开始匹配迪尼玛绳规格:");
    console.log("  dyneemaSpecId:", bearingCableParams.dyneemaSpecId);
    console.log("  可用规格数量:", allDyneemaSpecs.length);

    // 清除之前的选择
    setSelectedDyneemaSpec(null);

    // 如果有选择的规格ID且规格列表已加载
    if (bearingCableParams.dyneemaSpecId && allDyneemaSpecs.length > 0) {
      const spec = allDyneemaSpecs.find(
        (s) => s.id === bearingCableParams.dyneemaSpecId
      );
      if (spec) {
        console.log(`[迪尼玛绳规格匹配] 找到匹配的规格:`, spec);
        setSelectedDyneemaSpec(spec);
        // 触发重新计算
        setBearingCableParams((prev) => ({
          ...prev,
          dyneemaSpecId: prev.dyneemaSpecId,
        }));
      } else {
        console.log(
          `[迪尼玛绳规格匹配] 未找到ID为"${bearingCableParams.dyneemaSpecId}"的规格`
        );
        toast({
          variant: "warning",
          title: "迪尼玛绳规格未找到",
          description: `未找到ID为 "${bearingCableParams.dyneemaSpecId}" 的迪尼玛绳规格。`,
        });
      }
    } else {
      console.log("[迪尼玛绳规格匹配] 缺少规格ID或规格列表为空");
    }
  }, [bearingCableParams.dyneemaSpecId, allDyneemaSpecs, toast]);

  const handleConductorParamChange = useCallback(
    (key, value) => {
      console.log(`[导线参数变更] 变更前 - ${key}:`, conductorParams[key]);
      let processedValue = value;

      if (value === "") {
        processedValue = null;
      } else if (key === "conductorNumber") {
        const intValue = parseInt(value, 10);
        processedValue = isNaN(intValue) ? 0 : intValue;
      } else if (key === "maxSagAtHighestTemp") {
        const numValue = parseFloat(value);
        processedValue = isNaN(numValue) ? 0 : numValue;
      }

      console.log(`[导线参数变更] 变更后 - ${key}:`, processedValue);
      setConductorParams((prev) => ({ ...prev, [key]: processedValue }));
    },
    [conductorParams]
  );

  const handleBearingCableParamChange = useCallback(
    (key, value) => {
      console.log(`[承载索参数变更] 变更前 - ${key}:`, bearingCableParams[key]);
      const floatFields = [
        "cableDiameter",
        "cableBreakingForce",
        "safetyFactor",
        "dyneemaSafetyFactor",
        "highSuspensionPointHeight",
        "lowSuspensionPointHeight",
        "minClearance",
        "nettingInsulatorRodLength",
        "nettingInsulatorRodUnitWeight",
        "nettingRopeLength",
        "nettingRopeUnitWeight",
        "nettingAttachmentTotalWeight",
        "anchorRopeSafetyFactor",
      ];
      const integerFields = [
        "fallenConductorCount",
        "nettingInsulatorRodCount",
        "nettingRopeCount",
      ];

      let processedValue = value;

      if (value === "") {
        processedValue = null;
      } else if (floatFields.includes(key)) {
        const numValue = parseFloat(value);
        processedValue = isNaN(numValue) ? 0 : numValue;
        if (key === "anchorRopeSafetyFactor" && processedValue < 3.0) {
          processedValue = 3.0;
        }
      } else if (integerFields.includes(key)) {
        const intValue = parseInt(value, 10);
        processedValue = isNaN(intValue) ? 0 : intValue;
        if (key === "fallenConductorCount" && processedValue < 1) {
          processedValue = 1;
        }
      }

      console.log(`[承载索参数变更] 变更后 - ${key}:`, processedValue);
      setBearingCableParams((prev) => ({ ...prev, [key]: processedValue }));
    },
    [bearingCableParams]
  );

  // const nettingDeviceTotalWeight = useMemo(() => {
  //   console.log("[封网装置总重计算] 开始计算封网装置总重");
  //   const {
  //     nettingInsulatorRodCount,
  //     nettingInsulatorRodLength,
  //     nettingInsulatorRodUnitWeight,
  //     nettingRopeCount,
  //     nettingRopeLength,
  //     nettingRopeUnitWeight,
  //     nettingAttachmentTotalWeight,
  //   } = bearingCableParams;

  //   console.log("[封网装置总重计算] 计算参数:");
  //   console.log("  绝缘杆数量:", nettingInsulatorRodCount);
  //   console.log("  绝缘杆长度:", nettingInsulatorRodLength);
  //   console.log("  绝缘杆单重:", nettingInsulatorRodUnitWeight);
  //   console.log("  封网绳数量:", nettingRopeCount);
  //   console.log("  封网绳长度:", nettingRopeLength);
  //   console.log("  封网绳单重:", nettingRopeUnitWeight);
  //   console.log("  附件总重:", nettingAttachmentTotalWeight);

  //   const g = 9.8;

  //   const totalInsulatorRodWeightKg =
  //     (nettingInsulatorRodCount || 0) *
  //     (nettingInsulatorRodLength || 0) *
  //     (nettingInsulatorRodUnitWeight || 0);
  //   const totalNettingRopeWeightKg =
  //     (nettingRopeCount || 0) *
  //     (nettingRopeLength || 0) *
  //     (nettingRopeUnitWeight || 0);
  //   const totalAttachmentWeightKg = nettingAttachmentTotalWeight || 0;

  //   console.log("[封网装置总重计算] 分项重量:");
  //   console.log("  绝缘杆总重:", totalInsulatorRodWeightKg, "kg");
  //   console.log("  封网绳总重:", totalNettingRopeWeightKg, "kg");
  //   console.log("  附件总重:", totalAttachmentWeightKg, "kg");

  //   const totalWeightKg =
  //     totalInsulatorRodWeightKg +
  //     totalNettingRopeWeightKg +
  //     totalAttachmentWeightKg;
  //   const result = totalWeightKg * g;
  //   console.log("[封网装置总重计算] 结果:", result, "N");
  //   return result;
  // }, [bearingCableParams]);

  const nettingDeviceTotalWeight = parseFloat(scheme.insulband?.totalNettingDevicesWeight) || 0;

  
  const anchorRopeCalculationResults = useMemo(() => {
    console.log("[锚网绳计算] 开始计算锚网绳参数");
    const { anchorRopeSafetyFactor, fallenConductorCount } = bearingCableParams;
    const spanLength = crossingPoint?.spanLengths?.[0];
    const conductorWeightPerMeter = conductorSpec?.weightPerMeterNPerM;
    const KU = 1.2;

    console.log("[锚网绳计算] 计算参数:");
    console.log("  档距长度:", spanLength);
    console.log("  局部封网长度:", localNettingLength);
    console.log("  导线规格:", conductorSpec);
    console.log("  导线单位重量:", conductorWeightPerMeter);
    console.log("  封网装置总重:", nettingDeviceTotalWeight);
    console.log("  安全系数:", anchorRopeSafetyFactor);
    console.log("  落网导线数量:", fallenConductorCount);
    console.log("  不均匀系数KU:", KU);

    if (!spanLength || spanLength <= 0) {
      console.log("[锚网绳计算] 错误: 档距数据缺失或不合法");
      return {
        hasError: true,
        errorMessage:
          "跨越点档距数据缺失或不合法。请确保跨越点已设置有效档距。",
        type: "guidance",
      };
    }
    if (!localNettingLength || localNettingLength <= 0) {
      console.log("[锚网绳计算] 错误: 局部封网长度无效");
      return {
        hasError: true,
        errorMessage: "需要先在绝缘绳网计算器中完成计算以获得绝缘绳网长度。",
        type: "guidance",
      };
    }
    if (!conductorSpec) {
      console.log("[锚网绳计算] 错误: 导线规格数据缺失");
      return {
        hasError: true,
        errorMessage: "导线规格数据缺失。请检查导线型号及规格库加载情况。",
        type: "guidance",
      };
    }
    if (!conductorWeightPerMeter || conductorWeightPerMeter <= 0) {
      console.log("[锚网绳计算] 错误: 导线单位重量无效");
      return {
        hasError: true,
        errorMessage:
          "导线规格数据不完整，缺少单位长度重量。请检查导线规格定义。",
        type: "guidance",
      };
    }
    if (nettingDeviceTotalWeight === null || nettingDeviceTotalWeight <= 0) {
      console.log("[锚网绳计算] 错误: 封网装置总重无效");
      return {
        hasError: true,
        errorMessage: "请先输入封网装置各部件重量以计算封网装置总重。",
        type: "guidance",
      };
    }
    const currentAnchorRopeSafetyFactor = anchorRopeSafetyFactor || 3.0;
    if (currentAnchorRopeSafetyFactor < 3.0) {
      console.log("[锚网绳计算] 错误: 安全系数小于3.0");
      return {
        hasError: true,
        errorMessage: `锚网绳安全系数必须大于等于3.0。当前值：${currentAnchorRopeSafetyFactor}`,
        type: "inputError",
      };
    }

    const fallenConductorLength =
      (3 / 8) * (spanLength - localNettingLength) + localNettingLength;
    if (fallenConductorLength <= 0) {
      console.log("[锚网绳计算] 错误: 落网导线长度不合理");
      return {
        hasError: true,
        errorMessage: "计算所得落网导线长度不合理，请检查跨距和局部封网长度。",
        type: "calculationError",
      };
    }

    const nFallen = fallenConductorCount || 1;
    const fallenConductorLoadN =
      nFallen * fallenConductorLength * conductorWeightPerMeter;
    const totalLoadN = fallenConductorLoadN + nettingDeviceTotalWeight;
    const totalLoadKN = totalLoadN / 1000;

    const requiredBreakingForceKN =
      currentAnchorRopeSafetyFactor * totalLoadKN * KU;

    console.log("[锚网绳计算] 计算结果:");
    console.log("  落网导线长度:", fallenConductorLength.toFixed(2), "m");
    console.log("  落网导线荷载:", fallenConductorLoadN.toFixed(2), "N");
    console.log("  总荷载:", totalLoadKN.toFixed(2), "kN");
    console.log("  所需最小破断力:", requiredBreakingForceKN.toFixed(2), "kN");

    return {
      hasError: false,
      errorMessage: null,
      fallenConductorLength: fallenConductorLength.toFixed(2),
      totalLoadKN: totalLoadKN.toFixed(2),
      requiredBreakingForceKN: requiredBreakingForceKN.toFixed(2),
      unevennessCoefficient: KU,
      nFallenConductors: nFallen,
    };
  }, [
    bearingCableParams,
    conductorSpec,
    localNettingLength,
    crossingPoint?.spanLengths,
    nettingDeviceTotalWeight,
  ]);

  const calculateLocalNettingForces = useCallback(
    (spec, workConditionKey) => {
      console.log(`[承载索受力计算] 开始计算${workConditionKey}工况受力`);
      if (!spec || !localNettingLength || localNettingLength <= 0) {
        console.log(
          `[承载索受力计算] 缺少必要参数: spec=${!!spec}, localNettingLength=${localNettingLength}`
        );
        return null;
      }

      const cableSpan = crossingPoint?.spanLengths?.[0] || 0;
      if (cableSpan <= 0) {
        console.log(`[承载索受力计算] 档距无效: ${cableSpan}`);
        return {
          hasError: true,
          errorMessage: "跨越点档距数据缺失或不合法。",
          name: workConditionKey,
        };
      }

      const { maxSagAtHighestTemp } = conductorParams;
      const {
        highSuspensionPointHeight,
        lowSuspensionPointHeight,
        minClearance,
        dyneemaSafetyFactor,
        fallenCircuitType,
        fallenConductorCount,
      } = bearingCableParams;

      console.log(`[承载索受力计算] ${workConditionKey}工况参数:`);
      console.log("  迪尼玛绳规格:", spec);
      console.log("  档距:", cableSpan);
      console.log("  局部封网长度:", localNettingLength);
      console.log("  最高温最大弧垂:", maxSagAtHighestTemp);
      console.log("  高侧悬挂点高程:", highSuspensionPointHeight);
      console.log("  低侧悬挂点高程:", lowSuspensionPointHeight);
      console.log("  最小净空:", minClearance);
      console.log("  安全系数:", dyneemaSafetyFactor);
      console.log("  落网类型:", fallenCircuitType);
      console.log("  落网导线数量:", fallenConductorCount);

      if (
        highSuspensionPointHeight === null ||
        lowSuspensionPointHeight === null ||
        isNaN(highSuspensionPointHeight) ||
        isNaN(lowSuspensionPointHeight)
      ) {
        console.log("[承载索受力计算] 悬挂点高程无效");
        return {
          hasError: true,
          errorMessage: "请填写悬挂点高程。",
          name: workConditionKey,
        };
      }

      try {
        const L = cableSpan; // 水平档距
        const h = highSuspensionPointHeight - lowSuspensionPointHeight; // 悬挂点高差
        console.log(`[承载索受力计算] 水平档距: ${L}m, 高差: ${h}m`);

        // 迪尼玛绳基本参数
        const ropeUnitWeightNPerM = spec.linearDensity * 9.8; // 承载索自重 (N/m)
        const ropeBreakinForceN = spec.breakingForce * 1000; // 破断力转换为N
        console.log(
          `[承载索受力计算] 迪尼玛绳参数: 自重=${ropeUnitWeightNPerM}N/m, 破断力=${ropeBreakinForceN}N`
        );

        // 导线和封网装置参数
        const conductorUnitWeightNPerM =
          conductorSpec?.weightPerMeterNPerM || 0;
        console.log(
          `[承载索受力计算] 导线单位重量: ${conductorUnitWeightNPerM}N/m`
        );

        // 动载系数
        const Kd = fallenCircuitType === "single" ? 1.67 : 2.89;
        const Kh = 1.2; // 不均匀系数
        const n = fallenConductorCount || 1;
        console.log(
          `[承载索受力计算] 动载系数Kd=${Kd}, 不均匀系数Kh=${Kh}, 落网数量n=${n}`
        );

        // 封网装置分布荷载
        const localNettingTotalWeightN = nettingDeviceTotalWeight;
        const ΔγNetting = localNettingTotalWeightN / L;
        console.log(
          `[承载索受力计算] 封网装置总重=${localNettingTotalWeightN}N, 分摊荷载=${ΔγNetting}N/m`
        );

        // 导线荷载计算
        const fallenConductorLength =
          (3 / 8) * (L - localNettingLength) + localNettingLength;
        const fallenConductorTotalWeightN =
          n * fallenConductorLength * conductorUnitWeightNPerM;
        const ΔγConductorStatic = fallenConductorTotalWeightN / L;
        const ΔγConductorDynamic = ΔγConductorStatic * Kd * Kh;
        console.log(
          `[承载索受力计算] 落网导线长度=${fallenConductorLength}m, 总重=${fallenConductorTotalWeightN}N`
        );
        console.log(
          `[承载索受力计算] 导线静载=${ΔγConductorStatic}N/m, 动载=${ΔγConductorDynamic}N/m`
        );

        // 各工况的分布荷载
        const q1 = ropeUnitWeightNPerM; // 空载
        const q2 = ropeUnitWeightNPerM + ΔγNetting; // 安全放线
        const q3 = ropeUnitWeightNPerM + ΔγNetting + ΔγConductorStatic; // 事故静载
        const q4 = ropeUnitWeightNPerM + ΔγNetting + ΔγConductorDynamic; // 事故动载
        console.log(
          `[承载索受力计算] 各工况荷载: q1=${q1}, q2=${q2}, q3=${q3}, q4=${q4}`
        );

        const workConditionsDefinition = {
          noLoad: { q: q1, name: "空载状态", description: "仅承载索自重" },
          safeLine: {
            q: q2,
            name: "安全放线工况",
            description: "承载索自重 + 封网装置分布荷载",
          },
          accidentStatic: {
            q: q3,
            name: "事故静载状态",
            description: "承载索自重 + 封网装置 + 导线落网静荷载",
          },
          accidentDynamic: {
            q: q4,
            name: "事故动载状态",
            description: "承载索自重 + 封网装置 + 导线落网冲击荷载",
          },
        };

        // 求解架空线状态方程
        const solveStateEquation = () => {
          console.log("[承载索受力计算] 开始求解状态方程");
          let HMin = 10; // N
          let HMax = ropeBreakinForceN; // N

          const tolerance = 0.1;
          const maxIterations = 200;

          for (let iter = 0; iter < maxIterations; iter++) {
            if (HMax - HMin < tolerance) break;

            const H = (HMin + HMax) / 2;
            console.log(`[承载索受力计算] 迭代${iter}: H=${H.toFixed(2)}N`);

            // 计算各工况最大张力
            const calculateMaxTension = (qCurrentLoad) => {
              if (qCurrentLoad < 0.001) {
                return { TMax: H, xLow: L / 2, xHigh: L / 2 };
              }

              const xLowPoint = L / 2 - (H * h) / (qCurrentLoad * L);
              const xClampedLow = Math.max(0.1, Math.min(L - 0.1, xLowPoint));
              const xClampedHigh = L - xClampedLow;

              const TLowSupport = Math.sqrt(
                Math.pow(H, 2) + Math.pow(qCurrentLoad * xClampedLow, 2)
              );
              const THighSupport = Math.sqrt(
                Math.pow(H, 2) + Math.pow(qCurrentLoad * xClampedHigh, 2)
              );

              return {
                TMax: Math.max(TLowSupport, THighSupport),
                xLow: xClampedLow,
                xHigh: xClampedHigh,
              };
            };

            const res1 = calculateMaxTension(q1);
            const res2 = calculateMaxTension(q2);
            const res3 = calculateMaxTension(q3);
            const res4 = calculateMaxTension(q4);

            // 检查约束条件
            const tensionProgressionValid =
              res4.TMax >= res3.TMax &&
              res3.TMax >= res2.TMax &&
              res2.TMax >= res1.TMax &&
              res1.TMax > 0;
            console.log(
              tensionProgressionValid,
              "tensionProgressionValidtensionProgressionValidtensionProgressionValid"
            );

            const strengthConstraintValid =
              res4.TMax <= ropeBreakinForceN * 0.8;

            const currentDyneemaSafetyFactor = dyneemaSafetyFactor || 6;
            const staticSafetyFactor = ropeBreakinForceN / res3.TMax;
            const safetyConstraintValid =
              staticSafetyFactor >= currentDyneemaSafetyFactor;

            console.log(
              `[承载索受力计算] 约束检查: 张力顺序=${tensionProgressionValid}, 强度=${strengthConstraintValid}, 安全系数=${safetyConstraintValid}`
            );

            if (
              tensionProgressionValid &&
              strengthConstraintValid &&
              safetyConstraintValid
            ) {
              console.log(`[承载索受力计算] 找到有效解: H=${H.toFixed(2)}N`);
              return {
                HSolved: H,
                results: {
                  noLoad: res1,
                  safeLine: res2,
                  accidentStatic: res3,
                  accidentDynamic: res4,
                },
                staticSafetyFactor,
                isValid: true,
              };
            }

            if (
              !strengthConstraintValid ||
              !safetyConstraintValid ||
              !tensionProgressionValid
            ) {
              HMax = H;
            } else {
              HMin = H;
            }
          }

          console.log("[承载索受力计算] 未找到有效解");
          return {
            isValid: false,
            errorMessage: "无法找到满足所有工况约束的水平张力H。",
          };
        };

        const solutionResult = solveStateEquation();

        if (!solutionResult.isValid) {
          console.log(
            `[承载索受力计算] 计算失败: ${solutionResult.errorMessage}`
          );
          return {
            hasError: true,
            errorMessage:
              solutionResult.errorMessage || "无法找到满足所有工况约束的解",
            name: workConditionKey,
          };
        }

        const { HSolved, results, staticSafetyFactor } = solutionResult;
        console.log(
          `[承载索受力计算] 计算成功: H=${HSolved.toFixed(
            2
          )}N, 安全系数=${staticSafetyFactor.toFixed(2)}`
        );

        // 构建计算结果
        const allWorkConditionResults = {};
        const allowableStressTension =
          ropeBreakinForceN / (dyneemaSafetyFactor || 6);

        for (const [key, conditionDef] of Object.entries(
          workConditionsDefinition
        )) {
          const currentResult = results[key];
          const qCurrent = conditionDef.q;

          const sagFromLowSupport =
            (qCurrent * Math.pow(currentResult.xLow, 2)) / (2 * HSolved);
          const sagFromHighSupport =
            (qCurrent * Math.pow(currentResult.xHigh, 2)) / (2 * HSolved);
          const maxSagForDisplay = Math.max(
            sagFromLowSupport,
            sagFromHighSupport
          );
          const lowestPointElevation =
            lowSuspensionPointHeight - sagFromLowSupport;
          const actualClearance =
            lowestPointElevation - (maxSagAtHighestTemp || 0);

          allWorkConditionResults[key] = {
            name: conditionDef.name,
            description:
              key === "accidentStatic"
                ? `承载索自重 + 封网装置 + 导线落网静荷载（安全系数：${staticSafetyFactor.toFixed(
                    2
                  )}）`
                : conditionDef.description,
            maxTension: currentResult.TMax / 1000,
            allowableLoad: allowableStressTension / 1000,
            actualSafetyFactor: ropeBreakinForceN / currentResult.TMax,
            isStressOk: currentResult.TMax <= allowableStressTension,
            sag: maxSagForDisplay,
            lowestPointElevation: lowestPointElevation,
            actualClearance: actualClearance,
            isClearanceOk: actualClearance >= minClearance,
            horizontalTensionKN: HSolved / 1000,
            totalLoadNPerM: qCurrent,
            calculationInfo: {
              distributedLoadBreakdown: {
                ropeWeightNPerM: ropeUnitWeightNPerM,
                nettingLoadNPerM: ΔγNetting,
                conductorLoadNPerM: {
                  static: ΔγConductorStatic,
                  dynamic: ΔγConductorDynamic,
                },
              },
              KdKh: { Kd, Kh },
              calculatedStaticSafetyFactor: staticSafetyFactor,
              xLowSupportToLowestPoint: currentResult.xLow,
              xHighSupportToLowestPoint: currentResult.xHigh,
            },
          };
        }

        console.log(
          `[承载索受力计算] ${workConditionKey}工况结果:`,
          allWorkConditionResults[workConditionKey]
        );
        return allWorkConditionResults[workConditionKey];
      } catch (error) {
        console.error(
          `[承载索受力计算] 计算出错 (${workConditionKey}):`,
          error
        );
        return {
          hasError: true,
          errorMessage: `计算出错: ${error.message}`,
          name: workConditionKey,
          description: "",
          isStressOk: false,
          maxTension: Infinity,
        };
      }
    },
    [
      conductorSpec,
      localNettingLength,
      conductorParams,
      bearingCableParams,
      nettingDeviceTotalWeight,
      crossingPoint?.spanLengths,
    ]
  );

  const dyneemaCalculationResults = useMemo(() => {
    console.log("[迪尼玛绳计算] 开始综合计算流程");

    // 步骤1: 检查承载索类型
    console.log("[迪尼玛绳计算] 步骤1: 检查承载索类型");
    if (bearingCableParams.cableType !== "dyneemaRope") {
      console.log("[迪尼玛绳计算] 步骤1失败: 承载索类型不是迪尼玛绳");
      return {
        hasError: true,
        errorMessage: "当前承载索类型不是迪尼玛绳",
        data: null,
        recommendedSpecs: [],
        currentFactors: null,
      };
    }
    console.log("[迪尼玛绳计算] 步骤1成功: 承载索类型为迪尼玛绳");

    // 步骤2: 获取基本参数
    console.log("[迪尼玛绳计算] 步骤2: 收集基本参数");
    const { conductorNumber, maxSagAtHighestTemp } = conductorParams;
    const {
      highSuspensionPointHeight,
      lowSuspensionPointHeight,
      minClearance,
      dyneemaSafetyFactor,
      fallenCircuitType,
      fallenConductorCount,
    } = bearingCableParams;

    const cableSpan = crossingPoint?.spanLengths?.[0] || 100;

    const effectiveConductorNumber = conductorNumber || 1;
    const effectiveMaxSagAtHighestTemp = maxSagAtHighestTemp || 0;
    const effectiveDyneemaSafetyFactor = dyneemaSafetyFactor || 6;
    const effectiveFallenConductorCount = fallenConductorCount || 1;

    console.log("[迪尼玛绳计算] 步骤2参数收集:");
    console.log("  导线根数:", effectiveConductorNumber);
    console.log("  最高温最大弧垂:", effectiveMaxSagAtHighestTemp);
    console.log("  档距:", cableSpan);
    console.log("  安全系数:", effectiveDyneemaSafetyFactor);
    console.log("  导线规格:", conductorSpec);
    console.log("  迪尼玛绳规格数量:", allDyneemaSpecs.length);
    console.log("  局部封网长度:", localNettingLength);
    console.log("  高侧悬挂点高程:", highSuspensionPointHeight);
    console.log("  低侧悬挂点高程:", lowSuspensionPointHeight);

    // 步骤3: 验证必要参数
    console.log("[迪尼玛绳计算] 步骤3: 验证必要参数");
    const missingParams = [];
    if (
      highSuspensionPointHeight === null ||
      highSuspensionPointHeight === undefined ||
      isNaN(highSuspensionPointHeight)
    ) {
      missingParams.push("高侧悬挂点高程");
    }
    if (
      lowSuspensionPointHeight === null ||
      lowSuspensionPointHeight === undefined ||
      isNaN(lowSuspensionPointHeight)
    ) {
      missingParams.push("低侧悬挂点高程");
    }
    if (
      !bearingCableParams.dyneemaSpecId ||
      bearingCableParams.dyneemaSpecId.trim() === ""
    ) {
      missingParams.push("迪尼玛绳规格");
    }

    // 如果有缺失的参数，返回相应的错误信息
    if (missingParams.length > 0) {
      console.log(
        `[迪尼玛绳计算] 步骤3失败: 缺少必要参数: ${missingParams.join(", ")}`
      );
      return {
        hasError: true,
        errorMessage: `请填写以下参数: ${missingParams.join(", ")}`,
        data: null,
        recommendedSpecs: [],
        currentFactors: null,
      };
    }
    console.log("[迪尼玛绳计算] 步骤3成功: 必要参数完整");

    // 步骤4: 验证参数有效性
    console.log("[迪尼玛绳计算] 步骤4: 验证参数有效性");
    if (effectiveConductorNumber <= 0) {
      console.log("[迪尼玛绳计算] 步骤4失败: 导线根数必须大于0");
      return {
        hasError: true,
        errorMessage: "导线根数必须大于0",
        data: null,
        recommendedSpecs: [],
        currentFactors: null,
      };
    }
    if (
      effectiveMaxSagAtHighestTemp === null ||
      effectiveMaxSagAtHighestTemp <= 0
    ) {
      console.log("[迪尼玛绳计算] 步骤4失败: 最高温最大弧垂无效");
      return {
        hasError: true,
        errorMessage: "请填写最高温最大弧垂",
        data: null,
        recommendedSpecs: [],
        currentFactors: null,
      };
    }
    if (!cableSpan || cableSpan <= 0) {
      console.log("[迪尼玛绳计算] 步骤4失败: 档距无效");
      return {
        hasError: true,
        errorMessage: "承载索跨度必须大于0",
        data: null,
        recommendedSpecs: [],
        currentFactors: null,
      };
    }
    if (effectiveDyneemaSafetyFactor <= 0) {
      console.log("[迪尼玛绳计算] 步骤4失败: 安全系数无效");
      return {
        hasError: true,
        errorMessage: "迪尼玛绳安全系数必须大于0",
        data: null,
        recommendedSpecs: [],
        currentFactors: null,
      };
    }
    if (!conductorSpec) {
      console.log("[迪尼玛绳计算] 步骤4失败: 导线规格缺失");
      return {
        hasError: true,
        errorMessage: "请等待导线规格数据加载完成",
        data: null,
        recommendedSpecs: [],
        currentFactors: null,
      };
    }
    if (!Array.isArray(allDyneemaSpecs) || allDyneemaSpecs.length === 0) {
      console.log("[迪尼玛绳计算] 步骤4失败: 迪尼玛绳规格库为空");
      return {
        hasError: true,
        errorMessage: "迪尼玛绳规格库为空，请先在知识库中导入迪尼玛绳规格数据",
        data: null,
        recommendedSpecs: [],
        currentFactors: null,
      };
    }
    if (!localNettingLength || localNettingLength <= 0) {
      console.log("[迪尼玛绳计算] 步骤4失败: 局部封网长度无效");
      return {
        hasError: true,
        errorMessage:
          "需要先完成绝缘绳网计算以获得局部封网长度，请前往绝缘绳网标签页完成计算",
        data: null,
        recommendedSpecs: [],
        currentFactors: null,
      };
    }
    console.log("[迪尼玛绳计算] 步骤4成功: 所有参数有效");

    // 步骤5: 计算动载参数
    console.log("[迪尼玛绳计算] 步骤5: 计算动载参数");
    const Kd = fallenCircuitType === "single" ? 1.67 : 2.89;
    const Kh = 1.2;
    const n = effectiveFallenConductorCount;
    const currentFactors = { Kd, Kh, n };
    console.log("[迪尼玛绳计算] 步骤5结果: Kd=", Kd, "Kh=", Kh, "n=", n);

    // 步骤6: 定义规格计算函数
    console.log("[迪尼玛绳计算] 步骤6: 定义规格计算函数");
    const calculateForDyneemaSpec = (spec) => {
      if (!spec) return null;
      console.log(
        `[迪尼玛绳计算] 计算规格: ${spec.nominalDiameter}mm, 破断力${spec.breakingForce}kN`
      );

      try {
        const workConditions = [
          "noLoad",
          "safeLine",
          "accidentStatic",
          "accidentDynamic",
        ];
        const results = {};
        let maxOverallSag = 0;
        let hasErrorInConditions = false;
        let conditionErrorMessage = null;

        for (const conditionKey of workConditions) {
          const result = calculateLocalNettingForces(spec, conditionKey);
          if (result?.hasError) {
            hasErrorInConditions = true;
            conditionErrorMessage = result.errorMessage;
            break;
          }
          if (result) {
            results[conditionKey] = result;
            maxOverallSag = Math.max(maxOverallSag, result.sag);
          }
        }

        if (hasErrorInConditions) {
          console.log(
            `[迪尼玛绳计算] 规格${spec.id}计算出错: ${conditionErrorMessage}`
          );
          return {
            id: spec?.id,
            nominalDiameter: spec?.nominalDiameter,
            breakingForce: spec?.breakingForce,
            error: conditionErrorMessage,
          };
        }

        if (Object.keys(results).length === 0) {
          console.log(`[迪尼玛绳计算] 规格${spec.id}无计算结果`);
          return null;
        }

        const allStressOk = Object.values(results).every((r) => r.isStressOk);
        const overallClearanceMinActual = Math.min(
          ...Object.values(results).map((r) => r.actualClearance)
        );
        const isOverallClearanceOk = overallClearanceMinActual >= minClearance;

        const result = {
          id: spec.id,
          nominalDiameter: spec.nominalDiameter,
          breakingForce: spec.breakingForce,
          linearDensity: spec.linearDensity,
          effectiveCrossSectionalArea: spec.effectiveCrossSectionalArea,
          calculatedResults: {
            ropeSpec: {
              model: spec.nominalDiameter + "mm",
              linearDensity: spec.linearDensity,
              breakingForce: spec.breakingForce,
              effectiveArea: spec.effectiveCrossSectionalArea,
            },
            basicParams: {
              totalConductorWeight:
                (conductorSpec.weightPerMeterNPerM *
                  cableSpan *
                  effectiveConductorNumber) /
                1000,
              nettingDeviceWeight: nettingDeviceTotalWeight / 1000,
              ropeUnitWeight: spec.linearDensity * 9.8,
              localNettingLength: localNettingLength,
            },
            workConditions: results,
            clearanceCheck: {
              actualClearance: overallClearanceMinActual,
              minClearance: minClearance,
              isClearanceOk: isOverallClearanceOk,
              maxSagCondition:
                Object.entries(results).find(
                  ([_, r]) => r.sag === maxOverallSag
                )?.[1]?.name || "N/A",
            },
            overallAssessment: {
              allStressOk,
              isClearanceOk: isOverallClearanceOk,
              overallPass: allStressOk && isOverallClearanceOk,
              recommendation:
                allStressOk && isOverallClearanceOk
                  ? "该迪尼玛绳规格满足所有工况要求（基于DL/T 5301-2013附录D.3方法）"
                  : `该规格不满足要求。${
                      !allStressOk ? "存在强度不足的工况。" : ""
                    }${!isOverallClearanceOk ? "净空距离不足。" : ""}`,
            },
            requiredBreakingForce:
              Math.max(...Object.values(results).map((r) => r.maxTension)) *
              effectiveDyneemaSafetyFactor,
          },
        };

        console.log(
          `[迪尼玛绳计算] 规格${spec.id}计算完成:`,
          result.calculatedResults.overallAssessment
        );
        return result;
      } catch (error) {
        console.error(`[迪尼玛绳计算] 规格${spec?.id}计算出错:`, error);
        return {
          id: spec?.id,
          nominalDiameter: spec?.nominalDiameter,
          breakingForce: spec?.breakingForce,
          error: `计算出错: ${error.message}`,
        };
      }
    };

    // 步骤7: 计算所有规格
    console.log(
      `[迪尼玛绳计算] 步骤7: 计算所有${allDyneemaSpecs.length}种规格`
    );
    const allCalculatedSpecs = allDyneemaSpecs
      .map(calculateForDyneemaSpec)
      .filter((spec) => spec && !spec.error);
    console.log(
      `[迪尼玛绳计算] 步骤7结果: 有效计算结果${allCalculatedSpecs.length}种`
    );

    // 步骤8: 筛选推荐规格
    console.log("[迪尼玛绳计算] 步骤8: 筛选推荐规格");
    const recommendedSpecs = allCalculatedSpecs
      .filter(
        (specResult) =>
          specResult.calculatedResults?.overallAssessment?.overallPass
      )
      .sort(
        (a, b) =>
          (a.calculatedResults?.requiredBreakingForce || Infinity) -
          (b.calculatedResults?.requiredBreakingForce || Infinity)
      )
      .map((specResult) => ({
        ...specResult,
        isRecommended:
          specResult.calculatedResults?.overallAssessment?.overallPass,
      }));
    console.log(
      `[迪尼玛绳计算] 步骤8结果: 推荐规格数量${recommendedSpecs.length}种`
    );

    // 步骤9: 获取选中规格结果
    console.log("[迪尼玛绳计算] 步骤9: 获取选中规格结果");
    const selectedSpecResults = selectedDyneemaSpec
      ? allCalculatedSpecs.find(
          (specResult) => specResult.id === selectedDyneemaSpec.id
        )?.calculatedResults
      : null;
    console.log(
      `[迪尼玛绳计算] 步骤9结果: 选中规格${
        selectedSpecResults ? "存在" : "不存在"
      }`
    );

    console.log("[迪尼玛绳计算] 计算流程完成");
    return {
      hasError: false,
      errorMessage: null,
      data: selectedSpecResults,
      recommendedSpecs,
      currentFactors,
      isUsingD3Method: true,
    };
  }, [
    bearingCableParams,
    conductorParams,
    selectedDyneemaSpec,
    conductorSpec,
    allDyneemaSpecs,
    crossingPoint?.spanLengths,
    localNettingLength,
    calculateLocalNettingForces,
    nettingDeviceTotalWeight,
  ]);

  const steelStrandCalculationResults = useMemo(() => {
    console.log("[钢绞线计算] 开始计算钢绞线参数");
    if (bearingCableParams.cableType !== "steelStrand") {
      console.log("[钢绞线计算] 承载索类型不是钢绞线，跳过计算");
      return {
        hasError: true,
        errorMessage: "当前承载索类型不是钢绞线",
        data: null,
      };
    }
    if (!conductorSpec || isLoadingConductorSpec) {
      console.log("[钢绞线计算] 导线规格未加载完成");
      return {
        hasError: true,
        errorMessage: "等待导线规格数据加载",
        data: null,
      };
    }

    try {
      const { conductorNumber, maxSagAtHighestTemp } = conductorParams;
      const {
        lowSuspensionPointHeight,
        minClearance,
        safetyFactor,
        cableBreakingForce,
      } = bearingCableParams;
      const cableSpan = crossingPoint?.spanLengths?.[0] || 100;

      console.log("[钢绞线计算] 计算参数:");
      console.log("  导线根数:", conductorNumber);
      console.log("  最高温最大弧垂:", maxSagAtHighestTemp);
      console.log("  低侧悬挂点高程:", lowSuspensionPointHeight);
      console.log("  最小净空:", minClearance);
      console.log("  安全系数:", safetyFactor);
      console.log("  破断力:", cableBreakingForce);
      console.log("  档距:", cableSpan);
      console.log("  导线规格:", conductorSpec);

      const effectiveConductorNumber = conductorNumber || 1;
      const effectiveMaxSagAtHighestTemp = maxSagAtHighestTemp || 0;
      const effectiveSafetyFactor = safetyFactor || 3;
      const effectiveCableBreakingForce = cableBreakingForce || 0;
      const effectiveSupportHeight = lowSuspensionPointHeight || 0;

      if (effectiveConductorNumber <= 0) {
        console.log("[钢绞线计算] 错误: 导线根数必须大于0");
        return {
          hasError: true,
          errorMessage: "导线根数必须大于0",
          data: null,
        };
      }
      if (effectiveMaxSagAtHighestTemp <= 0) {
        console.log("[钢绞线计算] 错误: 最高温最大弧垂无效");
        return {
          hasError: true,
          errorMessage: "请填写最高温最大弧垂",
          data: null,
        };
      }
      if (!cableSpan || cableSpan <= 0) {
        console.log("[钢绞线计算] 错误: 档距无效");
        return {
          hasError: true,
          errorMessage: "承载索跨度必须大于0",
          data: null,
        };
      }
      if (effectiveSafetyFactor <= 0) {
        console.log("[钢绞线计算] 错误: 安全系数无效");
        return {
          hasError: true,
          errorMessage: "安全系数必须大于0",
          data: null,
        };
      }
      if (effectiveCableBreakingForce <= 0) {
        console.log("[钢绞线计算] 错误: 破断力无效");
        return { hasError: true, errorMessage: "破断力必须大于0", data: null };
      }
      if (
        lowSuspensionPointHeight === null ||
        isNaN(lowSuspensionPointHeight)
      ) {
        console.log("[钢绞线计算] 错误: 低侧悬挂点高程无效");
        return {
          hasError: true,
          errorMessage: "请填写低侧悬挂点高程以进行钢绞线简化计算。",
          data: null,
        };
      }

      const conductorWeightPerMeter = conductorSpec.weightPerMeterNPerM;
      const totalConductorWeight =
        (conductorWeightPerMeter * cableSpan * effectiveConductorNumber) / 1000;
      const unitLoadOnCable = totalConductorWeight / cableSpan;
      const assumedCableSag = Math.min(cableSpan / 20, 5);
      const horizontalTension =
        (unitLoadOnCable * Math.pow(cableSpan, 2)) / (8 * assumedCableSag);
      const maxTension =
        horizontalTension *
        Math.sqrt(1 + Math.pow((4 * assumedCableSag) / cableSpan, 2));
      const allowableLoad = effectiveCableBreakingForce / effectiveSafetyFactor;
      const actualSafetyFactor = effectiveCableBreakingForce / maxTension;
      const isStressOk = maxTension <= allowableLoad;
      const actualClearance =
        effectiveSupportHeight - effectiveMaxSagAtHighestTemp - assumedCableSag;
      const isClearanceOk = actualClearance >= minClearance;

      console.log("[钢绞线计算] 计算结果:");
      console.log("  总导线重量:", totalConductorWeight.toFixed(2), "kN");
      console.log("  单位荷载:", unitLoadOnCable.toFixed(3), "kN/m");
      console.log("  假设弧垂:", assumedCableSag.toFixed(2), "m");
      console.log("  最大张力:", maxTension.toFixed(1), "kN");
      console.log("  允许荷载:", allowableLoad.toFixed(1), "kN");
      console.log("  实际安全系数:", actualSafetyFactor.toFixed(2));
      console.log("  实际净空:", actualClearance.toFixed(2), "m");
      console.log("  强度是否满足:", isStressOk);
      console.log("  净空是否满足:", isClearanceOk);

      return {
        hasError: false,
        errorMessage: null,
        data: {
          totalConductorWeight: totalConductorWeight.toFixed(2),
          unitLoadOnCable: unitLoadOnCable.toFixed(3),
          assumedCableSag: assumedCableSag.toFixed(2),
          maxTension: maxTension.toFixed(1),
          allowableLoad: allowableLoad.toFixed(1),
          actualSafetyFactor: actualSafetyFactor.toFixed(2),
          isStressOk,
          actualClearance: actualClearance.toFixed(2),
          isClearanceOk,
        },
      };
    } catch (error) {
      console.error("[钢绞线计算] 计算出错:", error);
      return {
        hasError: true,
        errorMessage: `钢绞线计算出错: ${error.message}`,
        data: null,
      };
    }
  }, [
    conductorSpec,
    isLoadingConductorSpec,
    conductorParams,
    bearingCableParams,
    crossingPoint?.spanLengths,
  ]);

  const handleSave = useCallback(() => {
    console.log("[保存数据] 开始验证并保存数据");
    if (bearingCableParams.cableType === "dyneemaRope") {
      if (
        dyneemaCalculationResults.hasError ||
        !dyneemaCalculationResults.data
      ) {
        console.log("[保存数据] 失败: 迪尼玛绳计算存在错误或未选择规格");
        toast({
          variant: "destructive",
          title: "保存失败",
          description:
            dyneemaCalculationResults.errorMessage ||
            "迪尼玛绳计算存在错误或未选择规格。",
        });
        return;
      }
    } else if (bearingCableParams.cableType === "steelStrand") {
      if (steelStrandCalculationResults.hasError) {
        console.log("[保存数据] 失败: 钢绞线计算存在错误");
        toast({
          variant: "destructive",
          title: "保存失败",
          description:
            steelStrandCalculationResults.errorMessage ||
            "钢绞线计算存在错误。",
        });
        return;
      }
    }

    if (
      anchorRopeCalculationResults.hasError &&
      anchorRopeCalculationResults.type !== "guidance"
    ) {
      console.log("[保存数据] 失败: 锚网绳计算存在错误");
      toast({
        variant: "destructive",
        title: "保存失败",
        description: `锚网绳计算存在错误: ${anchorRopeCalculationResults.errorMessage}`,
      });
      return;
    }

    if (
      !anchorRopeCalculationResults.hasError &&
      (!bearingCableParams.anchorRopeMaterial ||
        !bearingCableParams.anchorRopeSpec)
    ) {
      console.log("[保存数据] 失败: 锚网绳材料和规格未填写");
      toast({
        variant: "destructive",
        title: "保存失败",
        description: "请填写锚网绳的选用材料和选用规格。",
      });
      return;
    }

    console.log(bearingCableParams, "bearingCableParamsbearingCableParams");
    console.log(999999999999);

    let updateData = {
      conductorBasicParams: {
        conductorCount: conductorParams.conductorNumber,
        conductorModel: conductorType,
        maximumSag: conductorParams.maxSagAtHighestTemp,
        weight: conductorSpec.weightPerMeterNPerM,
      },
      carryingCableConfig: {
        accessoryTotalWeight: bearingCableParams.nettingAttachmentTotalWeight,
        barLengthPerRoot: bearingCableParams.nettingInsulatorRodLength,
        barWeightPerMeter: bearingCableParams.nettingInsulatorRodUnitWeight,
        breakingForce: bearingCableParams.cableBreakingForce, //破断力
        cableType: bearingCableParams.cableType,
        diameter: selectedDyneemaSpec?.nominalDiameter,
        dyneemaRopeSpec: bearingCableParams.dyneemaSpecId,

        dyneemaNominalDiameter: `φ${selectedDyneemaSpec?.nominalDiameter}mm (${selectedDyneemaSpec?.breakingForce}kN)`,
        dyneemaBreakingForce: selectedDyneemaSpec?.breakingForce,
        dyneemaLinearDensity: selectedDyneemaSpec?.linearDensity,
        dyneemaEffectiveArea: selectedDyneemaSpec?.effectiveCrossSectionalArea,

        highSideSuspension: bearingCableParams.highSuspensionPointHeight,
        insulatorBarCount: bearingCableParams.nettingInsulatorRodCount,
        localNetLength: localNettingLength,
        lowSideSuspension: bearingCableParams.lowSuspensionPointHeight,
        minClearance: bearingCableParams.minClearance,
        ropeCount: bearingCableParams.nettingRopeCount,
        ropeLengthPerRoot: bearingCableParams.nettingRopeLength,
        ropeWeightPerMeter: bearingCableParams.nettingRopeUnitWeight,
        safetyFactor: bearingCableParams.dyneemaSafetyFactor, //安全系数
        totalDeviceWeight: nettingDeviceTotalWeight.toFixed(2),
      },
      anchorRopeCalculation: {
        fallenConductorLength:
          anchorRopeCalculationResults.fallenConductorLength,
        minBreakingForce: anchorRopeCalculationResults.requiredBreakingForceKN,
        safetyFactor: bearingCableParams.anchorRopeSafetyFactor,
        selectedMaterial: bearingCableParams.anchorRopeMaterial,
        selectedSpecification: bearingCableParams.anchorRopeSpec,
        splitConductorCount: bearingCableParams.fallenConductorCount,
        totalLoad: anchorRopeCalculationResults.totalLoadKN,
      },

      dynemaRopeResult: {
        netDropSituation: bearingCableParams.fallenCircuitType,
        splitConductorCount: bearingCableParams.fallenConductorCount,
        workingConditionCheck: [
          {
            clearance:
              dyneemaCalculationResults.data?.workConditions?.noLoad?.actualClearance?.toFixed(
                2
              ) || "",
            conditionType: "空载状态",
            maxTension:
              dyneemaCalculationResults.data?.workConditions?.noLoad?.maxTension?.toFixed(
                2
              ) || "",
            sag:
              dyneemaCalculationResults.data?.workConditions?.noLoad?.sag?.toFixed(
                2
              ) || "",
            strengthPassed:
              dyneemaCalculationResults.data?.workConditions?.noLoad
                ?.isStressOk || false,
          },
          {
            clearance:
              dyneemaCalculationResults.data?.workConditions?.safeLine?.actualClearance?.toFixed(
                2
              ) || "",
            conditionType: "安全放线工况",
            maxTension:
              dyneemaCalculationResults.data?.workConditions?.safeLine?.maxTension?.toFixed(
                2
              ) || "",
            sag:
              dyneemaCalculationResults.data?.workConditions?.safeLine?.sag?.toFixed(
                2
              ) || "",
            strengthPassed:
              dyneemaCalculationResults.data?.workConditions?.safeLine
                ?.isStressOk || false,
          },
          {
            clearance:
              dyneemaCalculationResults.data?.workConditions?.accidentStatic?.actualClearance?.toFixed(
                2
              ) || "",
            conditionType: "事故静载状态",
            maxTension:
              dyneemaCalculationResults.data?.workConditions?.accidentStatic?.maxTension?.toFixed(
                2
              ) || "",
            sag:
              dyneemaCalculationResults.data?.workConditions?.accidentStatic?.sag?.toFixed(
                2
              ) || "",
            strengthPassed:
              dyneemaCalculationResults.data?.workConditions?.accidentStatic
                ?.isStressOk || false,
          },
          {
            clearance:
              dyneemaCalculationResults.data?.workConditions?.accidentDynamic?.actualClearance?.toFixed(
                2
              ) || "",
            conditionType: "事故动载状态",
            maxTension:
              dyneemaCalculationResults.data?.workConditions?.accidentDynamic?.maxTension?.toFixed(
                2
              ) || "",
            sag:
              dyneemaCalculationResults.data?.workConditions?.accidentDynamic?.sag?.toFixed(
                2
              ) || "",
            strengthPassed:
              dyneemaCalculationResults.data?.workConditions?.accidentDynamic
                ?.isStressOk || false,
          },
        ],
      },

      conductorNumber: conductorParams.conductorNumber,
      maxSagAtHighestTemp: conductorParams.maxSagAtHighestTemp,
      bearingCableType: bearingCableParams.cableType,
      bearingCableDiameter: bearingCableParams.cableDiameter,
      bearingCableBreakingForce: bearingCableParams.cableBreakingForce,
      bearingCableSafetyFactor: bearingCableParams.safetyFactor,
      bearingCableDyneemaSpecId: bearingCableParams.dyneemaSpecId,
      bearingCableDyneemaSafetyFactor: bearingCableParams.dyneemaSafetyFactor,
      bearingCableHighSuspensionHeight:
        bearingCableParams.highSuspensionPointHeight,
      bearingCableLowSuspensionHeight:
        bearingCableParams.lowSuspensionPointHeight,
      bearingCableMinClearance: bearingCableParams.minClearance,
      nettingInsulatorRodCount: bearingCableParams.nettingInsulatorRodCount,
      nettingInsulatorRodLength: bearingCableParams.nettingInsulatorRodLength,
      nettingInsulatorRodUnitWeight:
        bearingCableParams.nettingInsulatorRodUnitWeight,
      nettingRopeCount: bearingCableParams.nettingRopeCount,
      nettingRopeLength: bearingCableParams.nettingRopeLength,
      nettingRopeUnitWeight: bearingCableParams.nettingRopeUnitWeight,
      nettingAttachmentTotalWeight:
        bearingCableParams.nettingAttachmentTotalWeight,
      fallenCircuitType: bearingCableParams.fallenCircuitType,
      fallenConductorCount: bearingCableParams.fallenConductorCount,
      anchorRopeSafetyFactor: bearingCableParams.anchorRopeSafetyFactor,
      anchorRopeMaterial: bearingCableParams.anchorRopeMaterial,
      anchorRopeSpec: bearingCableParams.anchorRopeSpec,

      nettingDeviceTotalWeight: nettingDeviceTotalWeight,
      anchorRopeCalculationResults: anchorRopeCalculationResults.hasError
        ? {
            error: anchorRopeCalculationResults.errorMessage,
            type: anchorRopeCalculationResults.type,
          }
        : {
            fallenConductorLength: parseFloat(
              anchorRopeCalculationResults.fallenConductorLength
            ),
            totalLoadKN: parseFloat(anchorRopeCalculationResults.totalLoadKN),
            requiredBreakingForceKN: parseFloat(
              anchorRopeCalculationResults.requiredBreakingForceKN
            ),
            unevennessCoefficient:
              anchorRopeCalculationResults.unevennessCoefficient,
            nFallenConductors: anchorRopeCalculationResults.nFallenConductors,
          },
    };

    if (bearingCableParams.cableType === "dyneemaRope") {
      updateData.bearingCableCalculationResults = {
        data: dyneemaCalculationResults.data,
        recommendedSpecs: dyneemaCalculationResults.recommendedSpecs,
        currentFactors: dyneemaCalculationResults.currentFactors,
        isUsingD3Method: true,
        localNettingLength: localNettingLength,
      };
    } else {
      updateData.bearingCableCalculationResults =
        steelStrandCalculationResults.data;
    }

    console.log("[保存数据] 准备保存的数据:", updateData);
    onUpdate(updateData);
    console.log("[保存数据] 保存成功");
    toast({
      title: "保存成功",
      description:
        bearingCableParams.cableType === "dyneemaRope"
          ? "承载索计算参数和结果已保存（基于D.3局部封网方法，考虑不等高），锚网绳结果已保存。"
          : "承载索计算参数和结果已保存（简化模型），锚网绳结果已保存。",
    });
  }, [
    dyneemaCalculationResults,
    steelStrandCalculationResults,
    conductorParams,
    bearingCableParams,
    onUpdate,
    toast,
    nettingDeviceTotalWeight,
    localNettingLength,
    anchorRopeCalculationResults,
    selectedDyneemaSpec, // 确保 selectedDyneemaSpec 被包含在依赖数组中
  ]);
  const formulas = [
    {
      name: "承载索四种工况",
      description: "空载、安全放线、事故动载、事故静载",
      formula: "H₀ < H₁ < H₂ < H₃",
      variables: [
        { symbol: "H₀", description: "空载水平张力", unit: "N" },
        { symbol: "H₁", description: "安全放线水平张力", unit: "N" },
        { symbol: "H₂", description: "事故动载水平张力", unit: "N" },
        { symbol: "H₃", description: "事故静载水平张力", unit: "N" },
      ],
    },
    {
      name: "弧垂计算",
      description: "各工况下的承载索弧垂",
      formula: "f = (ω·l²) / (8H·cosφ)",
      variables: [
        { symbol: "f", description: "弧垂", unit: "m" },
        { symbol: "ω", description: "单位长度重量", unit: "N/m" },
        { symbol: "l", description: "档距", unit: "m" },
        { symbol: "H", description: "水平张力", unit: "N" },
        { symbol: "φ", description: "高差角", unit: "度" },
      ],
    },
  ];
  return (
    <TooltipProvider>
      <div className="space-y-4">
        {/* 加载状态提示 */}
        {(isLoadingConductorSpec || isLoadingDyneemaSpecs) && (
          <Alert className="bg-blue-50 border-blue-200">
            <Info className="h-4 w-4 text-blue-600" />
            <AlertDescription>
              <div className="flex items-center gap-2">
                <span>正在加载规格数据...</span>
                {isLoadingConductorSpec && (
                  <Badge variant="outline" className="text-xs">
                    导线规格
                  </Badge>
                )}
                {isLoadingDyneemaSpecs && (
                  <Badge variant="outline" className="text-xs">
                    迪尼玛绳规格
                  </Badge>
                )}
              </div>
            </AlertDescription>
          </Alert>
        )}

        <FormulaDisplay
          standard="DL/T 5301-2013《输电线路张力架线施工工艺导则》附录D"
          formulas={formulas}
        />
        {bearingCableParams.cableType === "dyneemaRope" && (
          <Alert className="bg-green-50 border-green-200">
            <AlertDescription className="text-green-800 text-sm">
              <strong>D.3局部封网计算方法：</strong>
              当前计算采用DL/T 5301-2013附录D.3方法，考虑封网装置在局部长度
              {localNettingLength ? (
                <strong> ({localNettingLength.toFixed(1)}m) </strong>
              ) : (
                " (待计算) "
              )}
              上的实际荷载分布，并已考虑承载索悬挂点高差进行精确求解。
              {!localNettingLength && (
                <span className="block mt-1 text-xs text-amber-700">
                  ⚠️ 需要先完成绝缘绳网计算
                </span>
              )}
            </AlertDescription>
          </Alert>
        )}

        {/* 主要内容区域：左右分栏布局 */}
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          {/* 左侧栏：参数设置区域 */}
          <div className="space-y-4">
            {/* 导线基础参数 */}
            <Card className="h-fit">
              <CardHeader className="pb-3">
                <CardTitle className="flex items-center gap-2 text-lg">
                  <Settings2 className="w-4 h-4 text-blue-600" />
                  导线基础参数
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-3">
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                  <div className="p-2 bg-slate-50 rounded border">
                    <Label className="text-xs font-medium">导线型号</Label>
                    <Input
                      value={conductorType || ""}
                      readOnly
                      className="mt-1 h-8 bg-slate-100 cursor-not-allowed text-sm"
                    />
                  </div>
                  {isLoadingConductorSpec ? (
                    <div className="text-center py-2 text-gray-500 text-sm">
                      正在加载...
                    </div>
                  ) : !conductorSpec ? (
                    <div className="p-2 bg-red-50 rounded border text-center text-sm text-red-500">
                      请设置导线型号
                    </div>
                  ) : (
                    <div className="p-2 bg-slate-50 rounded border">
                      <Label className="text-xs font-medium">
                        单位重量 (N/m)
                      </Label>
                      <Input
                        value={conductorSpec.weightPerMeterNPerM || ""}
                        readOnly
                        className="mt-1 h-8 bg-slate-100 cursor-not-allowed text-sm"
                      />
                    </div>
                  )}
                </div>
                <div className="grid grid-cols-2 gap-3">
                  <div>
                    <Label className="text-xs font-medium">导线根数</Label>
                    <Input
                      type="number"
                      min="1"
                      value={conductorParams.conductorNumber ?? ""}
                      onChange={(e) =>
                        handleConductorParamChange(
                          "conductorNumber",
                          e.target.value
                        )
                      }
                      className="mt-1 h-8"
                    />
                  </div>
                  <div>
                    <Label className="text-xs font-medium">
                      最高温最大弧垂 (m)
                    </Label>
                    <Input
                      type="number"
                      step="0.1"
                      value={conductorParams.maxSagAtHighestTemp ?? ""}
                      onChange={(e) =>
                        handleConductorParamChange(
                          "maxSagAtHighestTemp",
                          e.target.value
                        )
                      }
                      placeholder="请输入"
                      className="mt-1 h-8"
                    />
                  </div>
                </div>
              </CardContent>
            </Card>

            {/* 承载索参数设置 */}
            <Card className="h-fit">
              <CardHeader className="pb-3">
                <CardTitle className="flex items-center gap-2 text-lg">
                  <Layers className="w-4 h-4 text-green-600" />
                  承载索参数
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-3">
                <div>
                  <Label className="text-xs font-medium">承载索类型</Label>
                  <Select
                    value={bearingCableParams.cableType}
                    onValueChange={(value) =>
                      handleBearingCableParamChange("cableType", value)
                    }
                  >
                    <SelectTrigger className="mt-1 h-8">
                      <SelectValue placeholder="选择类型" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="steelStrand">钢绞线</SelectItem>
                      <SelectItem value="dyneemaRope">迪尼玛绳</SelectItem>
                    </SelectContent>
                  </Select>
                </div>

                {/* 钢绞线 */}
                {bearingCableParams.cableType === "steelStrand" && (
                  <div className="grid grid-cols-3 gap-2 p-2 bg-gray-50 rounded border">
                    <div>
                      <Label className="text-xs">索径 (mm)</Label>
                      <Input
                        type="number"
                        value={bearingCableParams.cableDiameter ?? ""}
                        onChange={(e) =>
                          handleBearingCableParamChange(
                            "cableDiameter",
                            e.target.value
                          )
                        }
                        className="h-8"
                      />
                    </div>
                    <div>
                      <Label className="text-xs">破断力 (kN)</Label>
                      <Input
                        type="number"
                        value={bearingCableParams.cableBreakingForce ?? ""}
                        onChange={(e) =>
                          handleBearingCableParamChange(
                            "cableBreakingForce",
                            e.target.value
                          )
                        }
                        className="h-8"
                      />
                    </div>
                    <div>
                      <Label className="text-xs">安全系数</Label>
                      <Input
                        type="number"
                        step="0.1"
                        value={bearingCableParams.safetyFactor ?? ""}
                        onChange={(e) =>
                          handleBearingCableParamChange(
                            "safetyFactor",
                            e.target.value
                          )
                        }
                        className="h-8"
                      />
                    </div>
                  </div>
                )}
                {/* 迪尼玛绳 */}
                {bearingCableParams.cableType === "dyneemaRope" && (
                  <div className="space-y-2 p-2 bg-blue-50 rounded border">
                    {!isLoadingDyneemaSpecs && allDyneemaSpecs.length > 0 ? (
                      <>
                        <div className="grid grid-cols-2 gap-2">
                          <div>
                            <Label className="text-xs font-medium">
                              迪尼玛绳规格
                            </Label>
                            <Select
                              value={bearingCableParams.dyneemaSpecId || ""}
                              onValueChange={(value) =>
                                handleBearingCableParamChange(
                                  "dyneemaSpecId",
                                  value
                                )
                              }
                            >
                              <SelectTrigger className="mt-1 h-8">
                                <SelectValue placeholder="选择规格" />
                              </SelectTrigger>
                              <SelectContent>
                                {allDyneemaSpecs.map((spec) => (
                                  <SelectItem key={spec.id} value={spec.id}>
                                    φ{spec.nominalDiameter}mm (
                                    {spec.breakingForce}kN)
                                  </SelectItem>
                                ))}
                              </SelectContent>
                            </Select>
                          </div>
                          <div>
                            <Label className="text-xs font-medium">
                              安全系数
                            </Label>
                            <Input
                              type="number"
                              step="0.1"
                              value={
                                bearingCableParams.dyneemaSafetyFactor ?? ""
                              }
                              onChange={(e) =>
                                handleBearingCableParamChange(
                                  "dyneemaSafetyFactor",
                                  e.target.value
                                )
                              }
                              className="mt-1 h-8"
                            />
                          </div>
                        </div>
                        {selectedDyneemaSpec && (
                          <div className="grid grid-cols-2 gap-2 p-2 bg-white rounded border text-xs">
                            <div className="text-center">
                              <div className="text-gray-500">直径</div>
                              <div className="font-medium">
                                {selectedDyneemaSpec.nominalDiameter}mm
                              </div>
                            </div>
                            <div className="text-center">
                              <div className="text-gray-500">破断力</div>
                              <div className="font-medium">
                                {selectedDyneemaSpec.breakingForce}kN
                              </div>
                            </div>
                          </div>
                        )}
                      </>
                    ) : (
                      <div className="text-center py-2 text-gray-500 text-sm">
                        {isLoadingDyneemaSpecs
                          ? "正在加载规格库..."
                          : "规格库为空"}
                      </div>
                    )}
                  </div>
                )}

                {/* 悬挂点高程输入 */}
                <div className="grid grid-cols-2 gap-2">
                  <div>
                    <Label className="text-xs">
                      高侧悬挂点高程 (m) <span className="text-red-500">*</span>
                    </Label>
                    <Input
                      type="number"
                      step="0.1"
                      value={bearingCableParams.highSuspensionPointHeight ?? ""}
                      onChange={(e) =>
                        handleBearingCableParamChange(
                          "highSuspensionPointHeight",
                          e.target.value
                        )
                      }
                      className="h-8"
                      placeholder="例如: 120.5"
                    />
                  </div>
                  <div>
                    <Label className="text-xs">
                      低侧悬挂点高程 (m) <span className="text-red-500">*</span>
                    </Label>
                    <Input
                      type="number"
                      step="0.1"
                      value={bearingCableParams.lowSuspensionPointHeight ?? ""}
                      onChange={(e) =>
                        handleBearingCableParamChange(
                          "lowSuspensionPointHeight",
                          e.target.value
                        )
                      }
                      className="h-8"
                      placeholder="例如: 118.0"
                    />
                  </div>
                </div>

                {/* 最小净空 */}
                <div className="grid grid-cols-1 gap-2">
                  <div>
                    <Label className="text-xs">最小净空 (m)</Label>
                    <Input
                      type="number"
                      step="0.1"
                      value={bearingCableParams.minClearance ?? ""}
                      onChange={(e) =>
                        handleBearingCableParamChange(
                          "minClearance",
                          e.target.value
                        )
                      }
                      className="h-8"
                    />
                  </div>
                </div>

                {/* <div className="p-2 rounded border text-center bg-gray-50 border-gray-200">
                  <Label className="text-xs font-medium">局部封网长度</Label>
                  <div
                    className={`text-sm font-bold ${
                      localNettingLength ? "text-green-700" : "text-amber-700"
                    }`}
                  >
                    {localNettingLength
                      ? `${localNettingLength.toFixed(1)} m`
                      : "待绝缘绳网计算"}
                  </div>
                  <p
                    className={`text-xs mt-1 ${
                      localNettingLength ? "text-green-600" : "text-amber-600"
                    }`}
                  >
                    {localNettingLength
                      ? "来自绝缘绳网计算器"
                      : "需先完成绝缘绳网计算"}
                  </p>
                </div> */}

                {/* <Collapsible
                  open={isNettingWeightDetailsOpen}
                  onOpenChange={setIsNettingWeightDetailsOpen}
                >
                  <CollapsibleTrigger asChild>
                    <Button
                      variant="link"
                      className="p-0 h-auto text-blue-600 text-xs"
                    >
                      <ChevronDown
                        className={`w-3 h-3 mr-1 transition-transform ${
                          isNettingWeightDetailsOpen ? "rotate-180" : ""
                        }`}
                      />
                      封网装置重量计算
                    </Button>
                  </CollapsibleTrigger>
                  <CollapsibleContent className="pt-2 space-y-2">
                    <div className="grid grid-cols-2 gap-2 text-xs">
                      <div>
                        <Label className="text-xs">绝缘杆数量 (根)</Label>
                        <Input
                          type="number"
                          min="0"
                          value={
                            bearingCableParams.nettingInsulatorRodCount ?? ""
                          }
                          onChange={(e) =>
                            handleBearingCableParamChange(
                              "nettingInsulatorRodCount",
                              e.target.value
                            )
                          }
                          className="h-7"
                        />
                      </div>
                      <div>
                        <Label className="text-xs">杆长度 (m/根)</Label>
                        <Input
                          type="number"
                          step="0.1"
                          min="0"
                          value={
                            bearingCableParams.nettingInsulatorRodLength ?? ""
                          }
                          onChange={(e) =>
                            handleBearingCableParamChange(
                              "nettingInsulatorRodLength",
                              e.target.value
                            )
                          }
                          className="h-7"
                        />
                      </div>
                      <div>
                        <Label className="text-xs">杆单重 (kg/m)</Label>
                        <Input
                          type="number"
                          step="0.1"
                          min="0"
                          value={
                            bearingCableParams.nettingInsulatorRodUnitWeight ??
                            ""
                          }
                          onChange={(e) =>
                            handleBearingCableParamChange(
                              "nettingInsulatorRodUnitWeight",
                              e.target.value
                            )
                          }
                          className="h-7"
                        />
                      </div>
                      <div>
                        <Label className="text-xs">绳数量 (根)</Label>
                        <Input
                          type="number"
                          min="0"
                          value={bearingCableParams.nettingRopeCount ?? ""}
                          onChange={(e) =>
                            handleBearingCableParamChange(
                              "nettingRopeCount",
                              e.target.value
                            )
                          }
                          className="h-7"
                        />
                      </div>
                      <div>
                        <Label className="text-xs">绳长度 (m/根)</Label>
                        <Input
                          type="number"
                          step="0.1"
                          min="0"
                          value={bearingCableParams.nettingRopeLength ?? ""}
                          onChange={(e) =>
                            handleBearingCableParamChange(
                              "nettingRopeLength",
                              e.target.value
                            )
                          }
                          className="h-7"
                        />
                      </div>
                      <div>
                        <Label className="text-xs">绳单重 (kg/m)</Label>
                        <Input
                          type="number"
                          step="0.1"
                          min="0"
                          value={bearingCableParams.nettingRopeUnitWeight ?? ""}
                          onChange={(e) =>
                            handleBearingCableParamChange(
                              "nettingRopeUnitWeight",
                              e.target.value
                            )
                          }
                          className="h-7"
                        />
                      </div>
                      <div className="col-span-2">
                        <Label className="text-xs">附件总重 (kg)</Label>
                        <Input
                          type="number"
                          step="0.1"
                          min="0"
                          value={
                            bearingCableParams.nettingAttachmentTotalWeight ??
                            ""
                          }
                          onChange={(e) =>
                            handleBearingCableParamChange(
                              "nettingAttachmentTotalWeight",
                              e.target.value
                            )
                          }
                          className="h-7"
                        />
                      </div>
                    </div>
                  </CollapsibleContent>
                </Collapsible>

                <div className="p-2 bg-slate-50 rounded border text-center">
                  <Label className="text-xs font-medium">
                    计算所得封网装置总重
                  </Label>
                  <div className="text-sm font-bold text-slate-800">
                    {nettingDeviceTotalWeight.toFixed(2)} N
                  </div> 
                </div> */}
              </CardContent>
            </Card>
          </div>

          {/* 右侧栏：计算结果区域 */}
          <div className="space-y-4">
            {/* 锚网绳计算与选型 */}
            <Card className="h-fit">
              <CardHeader className="pb-3">
                <CardTitle className="flex items-center gap-2 text-lg">
                  <Anchor className="w-4 h-4 text-cyan-600" />
                  锚网绳计算与选型
                </CardTitle>
                <CardDescription>
                  根据事故静载状态计算锚网绳所需最小破断力，用户根据结果手动选型。
                </CardDescription>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  {/* 参数输入区域 */}
                  <div className="p-3 border rounded-lg bg-gray-50">
                    <h4 className="font-medium text-sm mb-3 text-gray-800">
                      计算参数
                    </h4>
                    <div className="grid grid-cols-2 gap-3">
                      <div>
                        <Label className="text-xs font-medium">
                          锚网绳安全系数 (Ks)
                        </Label>
                        <Input
                          type="number"
                          min="3.0"
                          step="0.1"
                          value={
                            bearingCableParams.anchorRopeSafetyFactor ?? ""
                          }
                          onChange={(e) =>
                            handleBearingCableParamChange(
                              "anchorRopeSafetyFactor",
                              e.target.value
                            )
                          }
                          className="mt-1 h-8"
                        />
                        <p className="text-xs text-gray-500 mt-1">
                          规范要求不小于3.0
                        </p>
                      </div>
                      <div>
                        <Label className="text-xs font-medium">
                          落网分裂导线数量 n
                        </Label>
                        <Input
                          type="number"
                          min="1"
                          step="1"
                          value={bearingCableParams.fallenConductorCount ?? ""}
                          onChange={(e) =>
                            handleBearingCableParamChange(
                              "fallenConductorCount",
                              e.target.value
                            )
                          }
                          className="mt-1 h-8"
                        />
                        <p className="text-xs text-gray-500 mt-1">
                          用于计算锚网绳荷载
                        </p>
                      </div>
                    </div>
                  </div>

                  {/* 计算结果显示 */}
                  {anchorRopeCalculationResults.hasError ? (
                    <Alert
                      variant={
                        anchorRopeCalculationResults.type === "guidance"
                          ? "default"
                          : "destructive"
                      }
                    >
                      <AlertTriangle className="h-4 w-4" />
                      <AlertDescription className="text-sm">
                        <p className="font-semibold">
                          {anchorRopeCalculationResults.type === "guidance"
                            ? "计算引导"
                            : "无法计算"}
                        </p>
                        <p className="text-xs">
                          {anchorRopeCalculationResults.errorMessage}
                        </p>
                      </AlertDescription>
                    </Alert>
                  ) : (
                    <div className="space-y-4">
                      {/* 计算过程与结果 */}
                      <div className="p-3 border rounded-lg bg-blue-50">
                        <h4 className="font-medium text-sm mb-3 text-blue-800">
                          计算结果
                        </h4>
                        <div className="grid grid-cols-1 sm:grid-cols-3 gap-3 text-xs">
                          <div className="p-3 bg-white rounded-lg border border-blue-200 text-center">
                            <div className="text-blue-600 font-medium">
                              落网导线长度
                            </div>
                            <div className="text-lg font-bold text-blue-800">
                              {
                                anchorRopeCalculationResults.fallenConductorLength
                              }{" "}
                              m
                            </div>
                            <p className="text-xs text-blue-500 mt-1">
                              按3/8公式计算
                            </p>
                          </div>
                          <div className="p-3 bg-white rounded-lg border border-blue-200 text-center">
                            <div className="text-purple-600 font-medium">
                              总荷载 (静载)
                            </div>
                            <div className="text-lg font-bold text-purple-800">
                              {anchorRopeCalculationResults.totalLoadKN} kN
                            </div>
                            <p className="text-xs text-purple-500 mt-1">
                              导线+封网装置重量
                            </p>
                          </div>
                          <div className="p-3 bg-white rounded-lg border border-red-200 text-center">
                            <div className="text-red-600 font-medium">
                              所需最小破断力
                            </div>
                            <div className="xl font-bold text-red-800">
                              {
                                anchorRopeCalculationResults.requiredBreakingForceKN
                              }{" "}
                              kN
                            </div>
                            <p className="text-xs text-red-500 mt-1">
                              含安全系数及不均匀系数
                            </p>
                          </div>
                        </div>
                      </div>

                      {/* 用户手动选型输入区域 */}
                      <div className="p-4 border-2 border-orange-200 rounded-lg bg-orange-50">
                        <div className="flex items-center gap-2 mb-3">
                          <div className="w-3 h-3 bg-orange-500 rounded-full"></div>
                          <h4 className="font-semibold text-sm text-orange-800">
                            锚网绳选型填写
                          </h4>
                          <Badge
                            variant="outline"
                            className="text-xs text-orange-600 border-orange-300"
                          >
                            用户手动填写
                          </Badge>
                        </div>
                        <p className="text-xs text-orange-700 mb-4">
                          请根据上述计算结果，选择合适的锚网绳材料和规格，确保实际破断力不小于{" "}
                          <strong>
                            {
                              anchorRopeCalculationResults.requiredBreakingForceKN
                            }{" "}
                            kN
                          </strong>
                        </p>

                        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                          <div className="space-y-2">
                            <Label className="text-sm font-medium text-gray-800">
                              选用材料 *
                            </Label>
                            <Input
                              value={
                                bearingCableParams.anchorRopeMaterial || ""
                              }
                              onChange={(e) =>
                                handleBearingCableParamChange(
                                  "anchorRopeMaterial",
                                  e.target.value
                                )
                              }
                              placeholder="例如：钢丝绳、钢绞线、聚乙烯绳等"
                              className="h-9"
                            />
                            <p className="text-xs text-gray-600">
                              根据破断力要求和现场条件选择合适材料
                            </p>
                          </div>

                          <div className="space-y-2">
                            <Label className="text-sm font-medium text-gray-800">
                              选用规格 *
                            </Label>
                            <Input
                              value={bearingCableParams.anchorRopeSpec || ""}
                              onChange={(e) =>
                                handleBearingCableParamChange(
                                  "anchorRopeSpec",
                                  e.target.value
                                )
                              }
                              placeholder="例如：6×19-16mm、φ18mm等"
                              className="h-9"
                            />
                            <p className="text-xs text-gray-600">
                              具体规格型号，含直径、结构等
                            </p>
                          </div>
                        </div>

                        {/* 选型提示信息 */}
                        <div className="mt-4 p-3 bg-white rounded-lg border border-orange-200">
                          <h5 className="text-xs font-medium text-gray-700 mb-2">
                            选型提示：
                          </h5>
                          <ul className="text-xs text-gray-600 space-y-1">
                            <li>• 钢丝绳：适用于大荷载，耐久性好，成本适中</li>
                            <li>
                              • 高强纤维绳：重量轻，绝缘性好，适用于带电作业
                            </li>
                            <li>• 确保所选绳索的实际破断力大于计算要求值</li>
                            <li>• 考虑现场施工条件和安装便利性</li>
                          </ul>
                        </div>

                        {/* 验证提示 */}
                        {bearingCableParams.anchorRopeMaterial &&
                          bearingCableParams.anchorRopeSpec && (
                            <div className="mt-3 p-2 bg-green-100 rounded border border-green-300">
                              <p className="text-xs text-green-700">
                                ✓ 已填写选型：
                                {bearingCableParams.anchorRopeMaterial} -{" "}
                                {bearingCableParams.anchorRopeSpec}
                              </p>
                            </div>
                          )}
                      </div>
                    </div>
                  )}
                </div>
              </CardContent>
            </Card>

            {/* 承载索计算结果 */}
            <Card className="h-fit">
              <CardHeader className="pb-3">
                <CardTitle className="flex items-center gap-2 text-lg">
                  <Calculator className="w-4 h-4 text-purple-600" />
                  {bearingCableParams.cableType === "dyneemaRope"
                    ? "迪尼玛绳计算结果"
                    : "钢绞线计算结果"}
                </CardTitle>
                {bearingCableParams.cableType === "dyneemaRope" ? (
                  <CardDescription>
                    <Alert className="bg-blue-50 border-blue-200">
                      <Info className="h-4 w-4 !text-blue-600" />
                      <AlertDescription className="text-blue-800 text-sm">
                        <strong>精确计算模型：</strong>
                        当前计算已考虑悬挂点高差，采用抛物线法精确求解。
                      </AlertDescription>
                    </Alert>
                  </CardDescription>
                ) : (
                  <CardDescription>
                    <Alert className="bg-orange-50 border-orange-200">
                      <Info className="h-4 w-4 text-orange-600" />
                      <AlertDescription className="text-sm text-orange-800">
                        钢绞线计算暂为简化模型，**未考虑悬挂点高差**。计算中采用{" "}
                        <span className="font-bold">低侧悬挂点高程</span>{" "}
                        进行校核。
                      </AlertDescription>
                    </Alert>
                  </CardDescription>
                )}
              </CardHeader>
              <CardContent>
                {bearingCableParams.cableType === "dyneemaRope" ? (
                  <>
                    <Collapsible
                      open={isAdvancedOpen}
                      onOpenChange={setIsAdvancedOpen}
                    >
                      <CollapsibleTrigger asChild>
                        <Button
                          variant="link"
                          className="p-0 h-auto text-blue-600 text-xs mb-2"
                        >
                          <ChevronDown
                            className={`w-3 h-3 mr-1 transition-transform ${
                              isAdvancedOpen ? "rotate-180" : ""
                            }`}
                          />
                          事故工况参数
                        </Button>
                      </CollapsibleTrigger>
                      <CollapsibleContent className="pb-3 space-y-2">
                        <div className="grid grid-cols-2 gap-2 p-2 border rounded bg-white">
                          <div>
                            <Label className="text-xs font-medium">
                              落网情况
                            </Label>
                            <Select
                              value={bearingCableParams.fallenCircuitType}
                              onValueChange={(value) =>
                                handleBearingCableParamChange(
                                  "fallenCircuitType",
                                  value
                                )
                              }
                            >
                              <SelectTrigger className="h-7">
                                <SelectValue placeholder="选择落网情况" />
                              </SelectTrigger>
                              <SelectContent>
                                <SelectItem value="single">单回线路</SelectItem>
                                <SelectItem value="double">
                                  同塔双回路
                                </SelectItem>
                              </SelectContent>
                            </Select>
                          </div>
                          <div>
                            <Label className="text-xs font-medium">
                              落网分裂导线数量 n
                            </Label>
                            <Input
                              type="number"
                              min="1"
                              step="1"
                              value={
                                bearingCableParams.fallenConductorCount ?? ""
                              }
                              onChange={(e) =>
                                handleBearingCableParamChange(
                                  "fallenConductorCount",
                                  e.target.value
                                )
                              }
                              className="h-7"
                            />
                          </div>
                        </div>
                        <div className="p-2 bg-blue-50 rounded-lg border border-blue-200">
                          <p className="text-xs text-blue-800">
                            <strong>参数说明：</strong>
                            事故动载荷载按D.3公式计算，并考虑局部加载对承载索张力和弧垂的影响。
                          </p>
                        </div>
                      </CollapsibleContent>
                    </Collapsible>

                    {dyneemaCalculationResults.hasError ? (
                      <Alert
                        variant={
                          dyneemaCalculationResults.errorMessage.includes(
                            "请填写"
                          )
                            ? "default"
                            : "destructive"
                        }
                      >
                        <AlertTriangle className="h-4 w-4" />
                        <AlertDescription className="text-sm">
                          {dyneemaCalculationResults.errorMessage}
                        </AlertDescription>
                      </Alert>
                    ) : !dyneemaCalculationResults.data ? (
                      <Alert className="bg-blue-50 border-blue-200">
                        <Info className="h-4 w-4 text-blue-600" />
                        <AlertDescription
                          className="text-sm"
                          onClick={() => {
                            console.log(
                              dyneemaCalculationResults,
                              "dyneemaCalculationResults"
                            );
                          }}
                        >
                          请填写悬挂点高程并选择迪尼玛绳规格以查看计算结果。
                        </AlertDescription>
                      </Alert>
                    ) : (
                      <div className="space-y-3">
                        <div>
                          <h5
                            className="font-medium text-sm mb-2"
                            onClick={() => {
                              console.log(
                                dyneemaCalculationResults.data.workConditions,
                                "dyneemaCalculationResults.data.workConditions"
                              );
                            }}
                          >
                            四种工况校核
                          </h5>
                          <div className="border rounded overflow-hidden max-h-40 overflow-y-auto">
                            <Table>
                              <TableHeader>
                                <TableRow className="text-xs">
                                  <TableHead className="p-2">工况</TableHead>
                                  <TableHead className="p-2">
                                    最大张力(kN)
                                  </TableHead>
                                  <TableHead className="p-2">
                                    最大弧垂(m)
                                  </TableHead>
                                  <TableHead className="p-2">净空(m)</TableHead>
                                  <TableHead className="p-2">强度</TableHead>
                                  <TableHead className="p-2">净空</TableHead>
                                </TableRow>
                              </TableHeader>
                              <TableBody>
                                {Object.entries(
                                  dyneemaCalculationResults.data.workConditions
                                ).map(([key, condition]) => (
                                  <TableRow key={key} className="text-xs">
                                    <TableCell className="p-2 font-medium">
                                      {condition.name}
                                    </TableCell>
                                    <TableCell className="p-2">
                                      {condition.maxTension.toFixed(2)}
                                    </TableCell>
                                    <TableCell className="p-2">
                                      {condition.sag.toFixed(3)}
                                    </TableCell>
                                    <TableCell className="p-2">
                                      {condition.actualClearance.toFixed(2)}
                                    </TableCell>
                                    <TableCell className="p-2">
                                      <Badge
                                        className={
                                          condition.isStressOk
                                            ? "bg-green-600"
                                            : "bg-red-600"
                                        }
                                      >
                                        {condition.isStressOk
                                          ? "通过"
                                          : "不通过"}
                                      </Badge>
                                    </TableCell>
                                    <TableCell className="p-2">
                                      <Badge
                                        className={
                                          condition.isClearanceOk
                                            ? "bg-green-600"
                                            : "bg-red-600"
                                        }
                                      >
                                        {condition.isClearanceOk
                                          ? "通过"
                                          : "不通过"}
                                      </Badge>
                                    </TableCell>
                                  </TableRow>
                                ))}
                              </TableBody>
                            </Table>
                          </div>
                        </div>

                        <div>
                          <h5 className="font-medium text-sm mb-2">综合评估</h5>
                          <Alert
                            className={
                              dyneemaCalculationResults.data.overallAssessment
                                .overallPass
                                ? "bg-green-50 border-green-200"
                                : "bg-red-50 border-red-200"
                            }
                          >
                            <AlertTriangle
                              className={`h-3 w-3 ${
                                dyneemaCalculationResults.data.overallAssessment
                                  .overallPass
                                  ? "text-green-600"
                                  : "text-red-600"
                              }`}
                            />
                            <AlertDescription
                              className={`text-xs ${
                                dyneemaCalculationResults.data.overallAssessment
                                  .overallPass
                                  ? "text-green-800"
                                  : "text-red-800"
                              }`}
                            >
                              {
                                dyneemaCalculationResults.data.overallAssessment
                                  .recommendation
                              }
                            </AlertDescription>
                          </Alert>
                        </div>
                      </div>
                    )}
                  </>
                ) : (
                  <div className="space-y-3">
                    {steelStrandCalculationResults.hasError ? (
                      <Alert variant="destructive">
                        <AlertTriangle className="h-4 w-4" />
                        <AlertDescription className="text-sm">
                          {steelStrandCalculationResults.errorMessage}
                        </AlertDescription>
                      </Alert>
                    ) : (
                      <>
                        <div className="grid grid-cols-3 gap-2 text-xs">
                          <div className="p-2 bg-blue-50 rounded border text-center">
                            <div className="text-blue-600 font-medium">
                              最大张力
                            </div>
                            <div className="text-sm font-bold text-blue-800">
                              {steelStrandCalculationResults.data.maxTension} kN
                            </div>
                          </div>
                          <div className="p-2 bg-green-50 rounded border text-center">
                            <div className="text-green-600 font-medium">
                              实际安全系数
                            </div>
                            <div className="text-sm font-bold text-green-800">
                              {
                                steelStrandCalculationResults.data
                                  .actualSafetyFactor
                              }
                            </div>
                          </div>
                          <div className="p-2 bg-purple-50 rounded border text-center">
                            <div className="text-purple-600 font-medium">
                              实际净空
                            </div>
                            <div className="text-sm font-bold text-purple-800">
                              {
                                steelStrandCalculationResults.data
                                  .actualClearance
                              }{" "}
                              m
                            </div>
                          </div>
                        </div>

                        <div className="flex gap-2">
                          <Badge
                            className={
                              steelStrandCalculationResults.data.isStressOk
                                ? "bg-green-600"
                                : "bg-red-600"
                            }
                          >
                            强度校核：
                            {steelStrandCalculationResults.data.isStressOk
                              ? "满足"
                              : "不满足"}
                          </Badge>
                          <Badge
                            className={
                              steelStrandCalculationResults.data.isClearanceOk
                                ? "bg-green-600"
                                : "bg-red-600"
                            }
                          >
                            净空校核：
                            {steelStrandCalculationResults.data.isClearanceOk
                              ? "满足"
                              : "不满足"}
                          </Badge>
                        </div>
                      </>
                    )}
                  </div>
                )}
              </CardContent>
            </Card>
          </div>
        </div>

        <div className="flex justify-end">
          <Button
            onClick={handleSave}
            disabled={
              (bearingCableParams.cableType === "dyneemaRope" &&
                (dyneemaCalculationResults.hasError ||
                  !dyneemaCalculationResults.data)) ||
              (bearingCableParams.cableType === "steelStrand" &&
                steelStrandCalculationResults.hasError) ||
              (anchorRopeCalculationResults.hasError &&
                anchorRopeCalculationResults.type !== "guidance") ||
              (!anchorRopeCalculationResults.hasError &&
                (!bearingCableParams.anchorRopeMaterial ||
                  !bearingCableParams.anchorRopeSpec))
            }
            className="px-6"
          >
            <Save className="w-4 h-4 mr-2" />
            保存计算结果
          </Button>
        </div>
      </div>
    </TooltipProvider>
  );
}
